package cn.com.dhcc.ddi.task.service.load;

import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.pub.core.handler.IAnalyzeCallBack;
import cn.com.dhcc.ddi.task.service.ChangeVo;
import cn.com.dhcc.ddi.task.service.ChangeVo.ColPro;
import cn.com.dhcc.ddi.task.service.ChangeVo.RowPro;
import org.apache.log4j.Logger;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

import java.io.IOException;
import java.util.*;

public class DataFileHandler extends DefaultHandler {
	private static Logger logger = Log.getLogger(LOGTYPE.ADAPTER);
	private IAnalyzeCallBack callBack;
	private long MaxNum = 0;
	private int idx = 0;
	private Properties props; // 用于存放名字属性对(key-value)
//	private List<String> sqlList = new ArrayList<String>();//更新后不用此属性
//	private Map<String, List<String>> tableSql = new LinkedHashMap<String, List<String>>();//
	private String currentType = "";
	private String currentTableName = "";
	private String currentName = ""; // 当前扫描到的键值
	private String colName = "";
	private String colType = "";
	private String isPK = "";
	private String id="";
	private StringBuffer currentValue = new StringBuffer(); // 当前名字对应的值
	@SuppressWarnings("unused")
	private String Name, Value;// 键值对
	private ChangeVo sqlVo = new ChangeVo();
	Map<String,List<RowPro>> proSql = new LinkedHashMap<String,List<RowPro>>();
	private List<RowPro> proList = new ArrayList<RowPro>();
    private RowPro tempPro = null;
    private Map<String, ColPro> proMap = new HashMap<String,ColPro>();
	public DataFileHandler(long maxNum, IAnalyzeCallBack callBack, String id) {
		super();
		this.MaxNum = maxNum;
		this.callBack = callBack;
		this.id=id;//一次解析的唯一标识
	}

	@Override
	public InputSource resolveEntity(String publicId, String systemId)
			throws IOException, SAXException {
		return super.resolveEntity(publicId, systemId);
	}

	@Override
	public void notationDecl(String name, String publicId, String systemId)
			throws SAXException {
		super.notationDecl(name, publicId, systemId);
	}

	@Override
	public void unparsedEntityDecl(String name, String publicId,
			String systemId, String notationName) throws SAXException {
		super.unparsedEntityDecl(name, publicId, systemId, notationName);
	}

	@Override
	public void setDocumentLocator(Locator locator) {
		super.setDocumentLocator(locator);
	}

	@Override
	public void startDocument() throws SAXException {
		// System.err.println("开始解析文档");
	}

	@Override
	public void endDocument() throws SAXException {
//		printChangeSql(sqlVo);
		if(callBack != null){
			try {
				sqlVo.setId(id);
				sqlVo.setOver(true);
				callBack.proccess(sqlVo);
			} catch (NiceException e) {
				logger.error(e);
			}
		}
	}

//	public static void main(String[] args) {
//		final HttpDataExchRecvService service=CM.getBean(HttpDataExchRecvService.class);
//		SAXParserFactory factory = SAXParserFactory.newInstance();
//		try {
//			SAXParser parser = factory.newSAXParser();
//			parser.parse(new File("e:\\kankan\\test.xml"), new CmDataFileHandler(FileAnalyzeHandler.MAX_NUM, new IAnalyzeCallBack() {
//				@Override
//				public void proccess(ChangeVo vo) throws NiceException {
//					service.execute(listVo, vo);
//				}
//			}));
//			
//		} catch (Exception e) {
//			logger.error("解析文件异常:"+e);
//		}
//	}
	
	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
		super.startPrefixMapping(prefix, uri);
	}

	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
		super.endPrefixMapping(prefix);
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equals("table")) {
			currentTableName = attributes.getValue(0);
		}
//		if (qName != "" && qName.equals("table")) {
//			if (currentType != "" && !currentType.equals(qName)) {
//				currentTableName = "";
//			}
//			currentType = qName;
//		}
		if (null != qName && "col".equals(qName)){
			colName = attributes.getValue("colName");
			colType = attributes.getValue("colType");
			isPK = attributes.getValue("isPK");
		}
		currentValue.delete(0, currentValue.length());
		this.currentName = qName;
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		String name = currentName; //当前节点的名称
		String value = currentValue.toString();
		if ("table".equals(qName)) {
//			System.out.println("current table :" + currentTableName);
			proMap = new HashMap<String, ColPro>();
			if (null == tempPro){
				return;
			}
//			proList.add(tempPro);
			List<RowPro> list = new ArrayList<RowPro>();
			list.addAll(proList);
			proSql.put(currentTableName, list);
			proList.clear();
		}
		//If current node is col and value is not null
		//如果当前节点为col并且值不为空的话，则进行组装
		if ("col".equals(name) && qName.equals(name)) {
			//组装ColPro实体
			ColPro pro = new ColPro();
			pro.setName(colName);
			pro.setType(colType);
			pro.setPk(isPK);
			pro.setValue(value);
			proMap.put(colName, pro);
		}
		if ("row".equals(qName)){
//			System.out.println("current qname:" + qName);
//			List<RowPro> list = new ArrayList<RowPro>();
//			proSql.put(currentTableName, list);
			tempPro = new RowPro();
			tempPro.setColMap(proMap);
			proMap = new HashMap<String, ColPro>();
			proList.add(tempPro);
			idx++;
			if (MaxNum == idx) {
				List<RowPro> list = new ArrayList<RowPro>();
				list.addAll(proList);
				proSql.put(currentTableName, list);
				proList.clear();

				Map<String,List<RowPro>> sql = new LinkedHashMap<String,List<RowPro>>();
				sql.putAll(proSql);
				sqlVo.setTableData(sql);
				if(callBack != null){
					try {
						sqlVo.setId(id);
						sqlVo.setOver(false);
						callBack.proccess(sqlVo);
					} catch (NiceException e) {
						logger.error(e);
					}
				}
				proSql.clear();
				sqlVo = new ChangeVo();
				idx = 0;
			}
		}

		if (qName != "" && "data".equals(qName)) {
			if (proSql != null) {
				Map<String,List<RowPro>> sql = new LinkedHashMap<String,List<RowPro>>();
				sql.putAll(proSql);
				sqlVo.setTableData(sql);
			}
			proList.clear();
			proSql.clear();
			tempPro = null;
		}
		this.currentName = "";
		currentValue.delete(0, currentValue.length());
		super.endElement(uri, localName, qName);
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		currentValue.append(ch, start, length);
	}

	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
		super.ignorableWhitespace(ch, start, length);
	}

	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {
		super.processingInstruction(target, data);
	}

	@Override
	public void skippedEntity(String name) throws SAXException {
		super.skippedEntity(name);
	}

	@Override
	public void warning(SAXParseException e) throws SAXException {
		super.warning(e);
	}

	@Override
	public void error(SAXParseException e) throws SAXException {
		super.error(e);
	}

	@Override
	public void fatalError(SAXParseException e) throws SAXException {
		super.fatalError(e);
	}
	public String getElementValue(String elementName) {
		// elementValue:对应于elementName的节点的属性值
		String elementValue = null;
		elementValue = props.getProperty(elementName);
		return elementValue;
	}

}
